package com.trungkent.smsbackup;

import java.io.IOException;
import com.box.androidlib.Box;
import com.box.androidlib.DAO.User;
import com.box.androidlib.ResponseListeners.GetAccountInfoListener;
import com.box.androidlib.activities.BoxAuthentication;
import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.DropboxAPI.Account;
import com.dropbox.client2.android.AndroidAuthSession;
import com.dropbox.client2.exception.DropboxException;
import com.dropbox.client2.session.TokenPair;
import com.trungkent.smsbackup.util.BoxnetUtils;
import com.trungkent.smsbackup.util.Constants;
import com.trungkent.smsbackup.util.DropboxUtils;
import com.trungkent.smsbackup.util.Utilities;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.TextUtils.TruncateAt;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class HomeActivity extends Activity {

	private LinearLayout linDropbox;
	private LinearLayout linBoxnet;
	private LinearLayout linSugarsync;

	private Button btnBackupSMS;
	private Button btnRestoreSMS;
	private Button btnBackupCallog;
	private Button btnRestoreCallog;

	DropboxAPI<AndroidAuthSession> mApi;

	private Account mDropboxAccount;

	private FIllDataTask mFIllDataTask;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);

		linDropbox = (LinearLayout) findViewById(R.id.linDropbox);
		linDropbox.setOnClickListener(onLinDropBoxClickListener);

		linBoxnet = (LinearLayout) findViewById(R.id.linBoxnet);
		linBoxnet.setOnClickListener(onLinBoxnetClickListener);

		linSugarsync = (LinearLayout) findViewById(R.id.linSugarsync);
		linSugarsync.setOnClickListener(onLinSugarsyncClickListener);

		btnBackupSMS = (Button) findViewById(R.id.btnBackupSMS);
		btnBackupSMS.setOnClickListener(onBtnBackupSMSClickListener);

		btnRestoreSMS = (Button) findViewById(R.id.btnRestoreSMS);
		btnRestoreSMS.setOnClickListener(onBtnRestoreSMSClickListener);

		btnBackupCallog = (Button) findViewById(R.id.btnBackupCallog);
		btnBackupCallog.setOnClickListener(onBtnBackupCallogClickListener);

		btnRestoreCallog = (Button) findViewById(R.id.btnRestoreCallog);
		btnRestoreCallog.setOnClickListener(onBtnRestoreCallogClickListener);

		if (DropboxUtils.getAccountName() != null) {
			TextView mDropboxName = (TextView) linDropbox
					.findViewById(R.id.txvDropboxConnectedAs);
			mDropboxName.setText(DropboxUtils.getAccountName());
			mDropboxName.setTextColor(Color.BLACK);
			mDropboxName.setTypeface(null, Typeface.BOLD);
			mDropboxName.setEllipsize(TruncateAt.END);
		}

		if (BoxnetUtils.getAccountName() != null) {
			TextView mDropboxName = (TextView) linBoxnet
					.findViewById(R.id.txvBoxnetConnectedAs);
			mDropboxName.setText(BoxnetUtils.getAccountName());
			mDropboxName.setTextColor(Color.BLACK);
			mDropboxName.setTypeface(null, Typeface.BOLD);
			mDropboxName.setEllipsize(TruncateAt.END);

		}

	}

	private OnClickListener onLinDropBoxClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// We create a new AuthSession so that we can use the Dropbox API.
			AndroidAuthSession session = DropboxUtils.getInstance(
					getApplicationContext()).buildSession();
			mApi = new DropboxAPI<AndroidAuthSession>(session);
			DropboxUtils.getInstance(getApplicationContext())
					.checkAppKeySetup();

			if (DropboxUtils.getAccountName() == null) {
				mApi.getSession().startAuthentication(HomeActivity.this);
			} else {
				// Start the remote authentication
			}
		}
	};

	private OnClickListener onLinBoxnetClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (BoxnetUtils.getAccountName() == null) {
				Intent intent = new Intent(getApplicationContext(),
						BoxAuthentication.class);
				intent.putExtra("API_KEY", Constants.BOX_NET_API_KEY);
				startActivityForResult(intent, Constants.AUTH_REQUEST_CODE);
			}
		}
	};

	private OnClickListener onLinSugarsyncClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

		}
	};

	private OnClickListener onBtnBackupSMSClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Intent mIntent = new Intent(getApplicationContext(),
					SMSActivity.class);
			startActivity(mIntent);
		}
	};

	private OnClickListener onBtnRestoreSMSClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

		}
	};

	private OnClickListener onBtnBackupCallogClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

		}
	};

	private OnClickListener onBtnRestoreCallogClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_home, menu);
		return true;
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (mApi != null) {
			AndroidAuthSession session = mApi.getSession();

			// The next part must be inserted in the onResume() method of the
			// activity from which session.startAuthentication() was called, so
			// that Dropbox authentication completes properly.
			if (session.authenticationSuccessful()) {
				mFIllDataTask = new FIllDataTask();
				mFIllDataTask.execute(DropboxUtils.DROPBOX_COMPLETED);
				try {
					// Mandatory call to complete the auth
					session.finishAuthentication();
					// Store it locally in our app for later use
					TokenPair tokens = session.getAccessTokenPair();
					DropboxUtils.getInstance(getApplicationContext())
							.storeKeys(tokens.key, tokens.secret);
				} catch (IllegalStateException e) {
					Utilities
							.showToast(
									getApplicationContext(),
									getString(R.string.error_drop_box_cannot_authenticate)
											+ e.getLocalizedMessage());
					Log.e("SMSCloudBackup", "Error authenticating", e);
				}
			}
		}

	}

	private class FIllDataTask extends AsyncTask<Integer, Void, Boolean> {

		@Override
		protected Boolean doInBackground(Integer... params) {
			boolean result = false;
			switch (params[0]) {
			case DropboxUtils.DROPBOX_COMPLETED:
				try {
					mDropboxAccount = mApi.accountInfo();
					result = true;
				} catch (DropboxException e) {
					result = false;
					e.printStackTrace();
				}
				break;

			default:
				break;
			}

			return result;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);

			if (result) {
				TextView mDropboxName = (TextView) linDropbox
						.findViewById(R.id.txvDropboxConnectedAs);
				mDropboxName.setText(mDropboxAccount.displayName);
				mDropboxName.setTextColor(Color.BLACK);
				mDropboxName.setEllipsize(TruncateAt.END);
				mDropboxName.setTypeface(null, Typeface.BOLD);

				DropboxUtils.storeUserName(mDropboxAccount.displayName);
			}

		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == Constants.AUTH_REQUEST_CODE) {
			if (resultCode == BoxAuthentication.AUTH_RESULT_SUCCESS) {
				// Store auth key in shared preferences.
				// BoxAuthentication activity will set the auth key into the
				// resulting intent extras, keyed as AUTH_TOKEN

				BoxnetUtils.storeAuthToken(data.getStringExtra("AUTH_TOKEN"));

				Box boxServiceHandler = Box
						.getInstance(Constants.BOX_NET_API_KEY);
				boxServiceHandler.getAccountInfo(
						data.getStringExtra("AUTH_TOKEN"),
						mGetAccountInfoListener);

			} else if (resultCode == BoxAuthentication.AUTH_RESULT_FAIL) {
				Toast.makeText(getApplicationContext(),
						"Unable to log into Box", Toast.LENGTH_LONG).show();
			}
		}
	}

	private GetAccountInfoListener mGetAccountInfoListener = new GetAccountInfoListener() {

		@Override
		public void onIOException(IOException e) {
			e.printStackTrace();
		}

		@Override
		public void onComplete(User boxUser, String status) {
			if (status
					.equals(GetAccountInfoListener.STATUS_GET_ACCOUNT_INFO_OK)
					&& boxUser != null) {
				TextView mBoxnetName = (TextView) linBoxnet
						.findViewById(R.id.txvBoxnetConnectedAs);
				mBoxnetName.setText(boxUser.getLogin());
				mBoxnetName.setTextColor(Color.BLACK);
				mBoxnetName.setEllipsize(TruncateAt.END);
				mBoxnetName.setTypeface(null, Typeface.BOLD);

				BoxnetUtils.storeUserName(boxUser.getLogin());

			} else if (status
					.equals(GetAccountInfoListener.STATUS_NOT_LOGGED_IN)) {
				Utilities.showToast(getApplicationContext(),
						R.string.error_box_net_not_logged_in);
			} else if (status
					.equals(GetAccountInfoListener.STATUS_APPLICATION_RESTRICTED)) {
				Toast.makeText(getApplicationContext(),
						"Please check your API key.", Toast.LENGTH_SHORT)
						.show();
			}
		}
	};
}
